package com.lzw.service.impl;

import com.lzw.bean.MenuNode;
import com.lzw.bean.UserRole;
import com.lzw.common.bean.Result;
import com.lzw.common.service.impl.BaseServiceImpl;
import com.lzw.mapper.MenuNodeMapper;
import com.lzw.mapper.UserRoleMapper;
import com.lzw.service.MenuNodeService;
import com.lzw.service.UserRoleService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 *
 * 用户角色相关服务
 * Created by Administrator on 2017/6/30 0030.
 */
@Service("userRoleService")
public class UserRoleServiceImpl extends BaseServiceImpl<UserRoleMapper,UserRole> implements UserRoleService {


    @Override
    public Result insertAll(List<UserRole> userRoles) {
        if(baseMapper.insertAll(userRoles)>=1){
            return  this.success("插入多条数据成功");
        }else{
            return  this.error("插入多条数据失败");
        }
    }

    @Override
    public Result deleteOther(int user_id, int[] role_ids) {
        if(baseMapper.deleteOther(user_id,role_ids)>=1){
            return  this.success("删除其他数据成功");
        }else{
            return  this.error("删除其他数据失败");
        }
    }

    @Override
    public Result setRole(int user_id, int[] role_ids){
        Result result1=this.deleteOther(user_id,role_ids);
        Result result2=null;
        if(role_ids!=null&&role_ids.length>0){
            List<UserRole> list=new ArrayList<>();
            for (int i=0;i<role_ids.length;i++){
                if(this.findByUserIdRoleId(user_id,role_ids[i])==null){
                    UserRole userRole=new UserRole();
                    userRole.setUserId(user_id);
                    userRole.setRoleId(role_ids[i]);
                    list.add(userRole);
                }

            }
            if(list.size()>0)
             result2=this.insertAll(list);
        }
        if(result1.getCode()==0||(result2!=null&&result2.getCode()==0)){
            return  this.success("授权成功！");
        }else{
            return  this.error("授权失败！");
        }

    }

    @Override
    public UserRole findByUserIdRoleId(int user_id, int role_id) {
        return baseMapper.findByUserIdRoleId(user_id,role_id);
    }
}
